
package com.ruoyi.info.service.impl;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.info.domain.*;
import com.ruoyi.info.mapper.AuditingMapper;
import com.ruoyi.info.mapper.ProductAdaptationMapper;
import com.ruoyi.info.mapper.ProductTypeMapper;
import com.ruoyi.info.vo.AuditingEnterpriseBase;
import com.ruoyi.info.vo.ProductAdaptationVo;
import com.ruoyi.system.mapper.SysDictDataMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.info.mapper.ProductMapper;
import com.ruoyi.info.service.IProductService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 产品信息Service业务层处理
 * 
 * @author wangshi
 * @date 2023-06-07
 */
@Service
public class ProductServiceImpl implements IProductService 
{
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductAdaptationMapper productAdaptationMapper;

    @Autowired
    private AuditingMapper auditingMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private ProductTypeMapper productTypeMapper;





    /**
     * 查询产品信息
     * 
     * @param id 产品信息主键
     * @return 产品信息
     */
    @Override
    public Product selectProductById(Long id)
    {
        return productMapper.selectProductById(id);
    }

    /**
     * 查询产品信息列表
     * 
     * @param product 产品信息
     * @return 产品信息
     */
    @Override
    public List<Product> selectProductList(Product product)
    {
        return productMapper.selectProductList(product);
    }

    /**
     * 新增产品信息
     * 
     * @param productAdaptationVo 产品信息和产品适配信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProduct(ProductAdaptationVo productAdaptationVo)
    {

        // 保存产品信息
        Product product = new Product();
        product.setCreateBy(productAdaptationVo.getCreateBy());
        product.setCreateTime(DateUtils.getNowDate());
        product.setpContacts(productAdaptationVo.getpContacts());
        product.setpIndustry(productAdaptationVo.getpIndustry());
        product.setpIntroduce(productAdaptationVo.getpIntroduce());
        product.setpKeyword(productAdaptationVo.getpKeyword());
        product.setpManufacturer(productAdaptationVo.getpManufacturer());
        product.setpVersion(productAdaptationVo.getpVersion());
        product.setpTel(productAdaptationVo.getpTel());
        product.setpName(productAdaptationVo.getpName());
        product.setpDataSource(productAdaptationVo.getpDataSource());
        product.setpType(productAdaptationVo.getpType());
        product.setRemark(productAdaptationVo.getRemark());

        int i = productMapper.insertProduct(product);
        if(i>0){
            int len = 0;
            // 保存产品适配信息
            List<ProductAdaptation> productAdaptations = productAdaptationVo.getProductAdaptations();
            if(productAdaptations == null || productAdaptations.size() == 0){
                throw new RuntimeException("添加失败");
            }
            for (int j = 0; j < productAdaptations.size(); j++) {
                ProductAdaptation productAdaptation = productAdaptations.get(j);
                productAdaptation.setPid(product.getId());
                productAdaptation.setCreateBy(productAdaptationVo.getCreateBy());
                productAdaptation.setCreateTime(DateUtils.getNowDate());
                len += productAdaptationMapper.insertProductAdaptation(productAdaptation);
            }
            if(len == productAdaptations.size()){
                return len;
            }else{
                throw new RuntimeException("添加失败");
            }
        }
        return -1;
    }

    /**
     * 修改产品信息
     * 
     * @param productAdaptationVo 产品信息和产品适配信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProduct(ProductAdaptationVo productAdaptationVo)
    {
        // 保存产品信息
        Product product = new Product();
        product.setUpdateBy(productAdaptationVo.getUpdateBy());
        product.setUpdateTime(DateUtils.getNowDate());
        product.setpContacts(productAdaptationVo.getpContacts());
        product.setpIndustry(productAdaptationVo.getpIndustry());
        product.setpIntroduce(productAdaptationVo.getpIntroduce());
        product.setpKeyword(productAdaptationVo.getpKeyword());
        product.setpManufacturer(productAdaptationVo.getpManufacturer());
        product.setpVersion(productAdaptationVo.getpVersion());
        product.setpTel(productAdaptationVo.getpTel());
        product.setpName(productAdaptationVo.getpName());
        product.setpDataSource(productAdaptationVo.getpDataSource());
        product.setpType(productAdaptationVo.getpType());
        product.setId(productAdaptationVo.getId());
        product.setRemark(productAdaptationVo.getRemark());
        product.setpStatus("0");
        int i = productMapper.updateProduct(product);
        if(i > 0){
            productAdaptationMapper.deleteProductAdaptationByProductId(productAdaptationVo.getId());
            int len = 0;
            // 保存产品适配信息
            List<ProductAdaptation> productAdaptations = productAdaptationVo.getProductAdaptations();
            if(productAdaptations == null || productAdaptations.size() == 0){
                throw new RuntimeException("修改失败");
            }
            for (int j = 0; j < productAdaptations.size(); j++) {
                ProductAdaptation productAdaptation = productAdaptations.get(j);
                productAdaptation.setPid(product.getId());
                productAdaptation.setCreateBy(productAdaptationVo.getCreateBy());
                productAdaptation.setCreateTime(DateUtils.getNowDate());
                len += productAdaptationMapper.insertProductAdaptation(productAdaptation);
            }
            if(len == productAdaptations.size()){
                return len;
            }else{
                throw new RuntimeException("修改失败");
            }

        }
        return -1;
    }

    /**
     * 批量删除产品信息
     * 
     * @param ids 需要删除的产品信息主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(Long[] ids)
    {
        return productMapper.deleteProductByIds(ids);
    }

    /**
     * 删除产品信息信息
     * 
     * @param id 产品信息主键
     * @return 结果
     */
    @Override
    public int deleteProductById(Long id)
    {
        return productMapper.deleteProductById(id);
    }

    /**
     * 导出产品信息
     */
    public void exportProduct(HttpServletResponse response, Product product) throws IOException{
        XSSFWorkbook workbook = new XSSFWorkbook();
        List<Product> products = productMapper.selectProductList(product);
        try{
            XSSFSheet sheet = workbook.createSheet("产品信息");
            XSSFSheet adSheet = workbook.createSheet("适配信息");
            String[] adLabels = new String[]{
                    "产品序号",
                    "适配OS",
                    "适配时间",
                    "适配OS类型",
                    "适配状态",
                    "适配OS版本",
                    "兼容等级",
                    "OS小版本",
                    "认证状态",
                    "适配平台",
                    "收费/免费",
                    "适配CPU型号",
                    "上架情况",
                    "适配验证情况",
                    "备注"
            };
            XSSFRow adHeaderRow = adSheet.createRow(0);
            for (int j = 0; j < adLabels.length; j++) {
                XSSFCell countryCell = adHeaderRow.createCell(j);
                countryCell.setCellValue(adLabels[j]);
            }
            String[] labels = new String[]{
                    "产品序号",
                    "产品名称",
                    "产品类型",
                    "行业",
                    "版本型号",
                    "产品介绍",
                    "厂商",
                    "联系人",
                    "联系方式",
                    "关键词",
                    "数据来源",
                    "备注"
            };
            XSSFRow headerRow = sheet.createRow(0);
            for (int j = 0; j < labels.length; j++) {
                XSSFCell countryCell = headerRow.createCell(j);
                countryCell.setCellValue(labels[j]);
            }
            List<ProductType> productTypes = productTypeMapper.selectProductTypeList(new ProductType());
            for (int i = 0; i < products.size(); i++) {
                XSSFRow row = sheet.createRow(i + 1);
                //                    产品序号
                XSSFCell countryCell = row.createCell(0);
                countryCell.setCellValue(i+1);
                //                    产品名称
                XSSFCell countryCell1 = row.createCell(1);
                countryCell1.setCellValue(products.get(i).getpName());

                //                    产品类型
                XSSFCell countryCell2= row.createCell(2);
//            List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                for (int j = 0; j < productTypes.size(); j++) {
                    if (products.get(i).getpType().equals(productTypes.get(j).getLevelCode())) {
                        countryCell2.setCellValue(productTypes.get(j).getLevelName().replace(",","-"));
                        break;
                    }
                }

//            行业
                XSSFCell countryCell3= row.createCell(3);
                List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                for (int j = 0; j < productIndustry.size(); j++) {
                    if (products.get(i).getpIndustry().equals(productIndustry.get(j).getDictValue())) {
                        countryCell3.setCellValue(productIndustry.get(j).getDictLabel());
                        break;
                    }
                }

                //                    版本型号
                XSSFCell countryCell4 = row.createCell(4);
                countryCell4.setCellValue(products.get(i).getpName());
                //                    产品介绍
                XSSFCell countryCell5 = row.createCell(5);
                countryCell5.setCellValue(products.get(i).getpIntroduce());
                //                    厂商
                XSSFCell countryCell6 = row.createCell(6);
                countryCell6.setCellValue(products.get(i).getpManufacturer());
                //                    联系人
                XSSFCell countryCell7 = row.createCell(7);
                countryCell7.setCellValue(products.get(i).getpContacts());
                //                    联系方式
                XSSFCell countryCell8 = row.createCell(8);
                countryCell8.setCellValue(products.get(i).getpTel());
                //                    关键词
                XSSFCell countryCell9 = row.createCell(9);
                countryCell9.setCellValue(products.get(i).getpKeyword());
                //                    数据来源
                XSSFCell countryCell10 = row.createCell(10);
                countryCell10.setCellValue(products.get(i).getpDataSource());
                //                    备注
                XSSFCell countryCell11 = row.createCell(11);
                countryCell11.setCellValue(products.get(i).getRemark());
                exportProductAdaptation(adSheet,products.get(i).getId(),i+1);
            }
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            workbook.write(response.getOutputStream());
        }finally {
            workbook.close();
        }
    }

    /**
     * 配合产品信息导出功能
     * @param sheet 工作表
     * @param productId 产品id
     * @param index 产品索引
     */
    public void exportProductAdaptation( XSSFSheet sheet,Long productId,int index){

        ProductAdaptation productAdaptation = new ProductAdaptation();
        productAdaptation.setPid(productId);
        List<ProductAdaptation> productAdaptations = productAdaptationMapper.selectProductAdaptationList(productAdaptation);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < productAdaptations.size(); i++) {
            XSSFRow row = sheet.createRow(i + 1);
            //                    产品序号
            XSSFCell countryCell = row.createCell(0);
            countryCell.setCellValue(index);
//            适配os
            XSSFCell countryCell1= row.createCell(1);
            List<SysDictData> auditionOs = sysDictDataMapper.selectDictDataByType("audition_os");
            for (int j = 0; j < auditionOs.size(); j++) {
                if (productAdaptations.get(i).getPaOs().equals(auditionOs.get(j).getDictValue())) {
                    countryCell1.setCellValue(auditionOs.get(j).getDictLabel());
                    break;
                }
            }
//            适配时间
            XSSFCell countryCell2= row.createCell(2);
            countryCell2.setCellValue(sdf.format(productAdaptations.get(i).getPaTime()));
            //            适配OS类型
            XSSFCell countryCell3= row.createCell(3);
            countryCell3.setCellValue(productAdaptations.get(i).getPaType());
            //            适配状态
            XSSFCell countryCell4= row.createCell(4);
            List<SysDictData> auditionStatus = sysDictDataMapper.selectDictDataByType("auditing_status");
            for (int j = 0; j < auditionStatus.size(); j++) {
                if (productAdaptations.get(i).getPaAuthenticationStatus().equals(auditionStatus.get(j).getDictValue())) {
                    countryCell4.setCellValue(auditionStatus.get(j).getDictLabel());
                    break;
                }
            }
//            适配OS版本
            XSSFCell countryCell5= row.createCell(5);
            countryCell5.setCellValue(productAdaptations.get(i).getPaVersion());

            //            兼容等级
            XSSFCell countryCell6= row.createCell(6);
            List<SysDictData> compatibilityLevel = sysDictDataMapper.selectDictDataByType("compatibility_level");
            for (int j = 0; j < compatibilityLevel.size(); j++) {
                if (productAdaptations.get(i).getPaLevel().equals(compatibilityLevel.get(j).getDictValue())) {
                    countryCell6.setCellValue(compatibilityLevel.get(j).getDictLabel());
                    break;
                }
            }
            //            OS小版本
            XSSFCell countryCell7= row.createCell(7);
            countryCell7.setCellValue(productAdaptations.get(i).getPaMinVersion());
            //            认证状态
            XSSFCell countryCell8= row.createCell(8);
            List<SysDictData> certificationStatus = sysDictDataMapper.selectDictDataByType("certification_status");
            for (int j = 0; j < certificationStatus.size(); j++) {
                if (productAdaptations.get(i).getPaLevel().equals(certificationStatus.get(j).getDictValue())) {
                    countryCell8.setCellValue(certificationStatus.get(j).getDictLabel());
                    break;
                }
            }
            //            适配平台
            XSSFCell countryCell9= row.createCell(9);
            List<SysDictData> adaptationPlatform = sysDictDataMapper.selectDictDataByType("adaptation_platform");
            for (int j = 0; j < adaptationPlatform.size(); j++) {
                if (productAdaptations.get(i).getPaPlatform().equals(adaptationPlatform.get(j).getDictValue())) {
                    countryCell9.setCellValue(adaptationPlatform.get(j).getDictLabel());
                    break;
                }
            }
            //            收费/免费
            XSSFCell countryCell10= row.createCell(10);
            List<SysDictData> auditingCost = sysDictDataMapper.selectDictDataByType("auditing_cost");
            for (int j = 0; j < auditingCost.size(); j++) {
                if (productAdaptations.get(i).getPaPlatform().equals(auditingCost.get(j).getDictValue())) {
                    countryCell10.setCellValue(auditingCost.get(j).getDictLabel());
                    break;
                }
            }
            //            适配CPU型号
            XSSFCell countryCell11= row.createCell(11);
            List<SysDictData> adaptedCpuModel = sysDictDataMapper.selectDictDataByType("adapted_cpu_model");
            for (int j = 0; j < adaptedCpuModel.size(); j++) {
                if (productAdaptations.get(i).getPaCpu().equals(adaptedCpuModel.get(j).getDictValue())) {
                    countryCell11.setCellValue(adaptedCpuModel.get(j).getDictLabel());
                    break;
                }
            }
            //            上架情况
            XSSFCell countryCell12= row.createCell(12);
            List<SysDictData> auditingListing = sysDictDataMapper.selectDictDataByType("auditing_listing");
            for (int j = 0; j < auditingListing.size(); j++) {
                if (productAdaptations.get(i).getPaCpu().equals(auditingListing.get(j).getDictValue())) {
                    countryCell12.setCellValue(auditingListing.get(j).getDictLabel());
                    break;
                }
            }
            //            适配验证情况
            XSSFCell countryCell13= row.createCell(13);
            List<SysDictData> adaptationVerificationStatus = sysDictDataMapper.selectDictDataByType("adaptation_verification_status");
            for (int j = 0; j < adaptationVerificationStatus.size(); j++) {
                if (productAdaptations.get(i).getPaCpu().equals(adaptationVerificationStatus.get(j).getDictValue())) {
                    countryCell13.setCellValue(adaptationVerificationStatus.get(j).getDictLabel());
                    break;
                }
            }
            //            备注
            XSSFCell countryCell14= row.createCell(14);
            countryCell14.setCellValue(productAdaptations.get(i).getPaRemark());


        }

    }

    /**
     * 导出案例信息模板
     */
    public void templateDownload(HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
       try{
           XSSFSheet sheet = workbook.createSheet("产品信息");
           XSSFSheet adSheet = workbook.createSheet("适配信息");
           String[] adLabels = new String[]{
                   "产品序号",
                   "适配OS",
                   "适配时间",
                   "适配OS类型",
                   "适配状态",
                   "适配OS版本",
                   "兼容等级",
                   "OS小版本",
                   "认证状态",
                   "适配平台",
                   "收费/免费",
                   "适配CPU型号",
                   "上架情况",
                   "适配验证情况",
                   "备注"
           };
           XSSFRow adHeaderRow = adSheet.createRow(0);
           for (int j = 0; j < adLabels.length; j++) {
               XSSFCell countryCell = adHeaderRow.createCell(j);
               countryCell.setCellValue(adLabels[j]);
           }
           String[] labels = new String[]{
                   "产品序号",
                   "产品名称",
                   "产品类型",
                   "行业",
                   "版本型号",
                   "产品介绍",
                   "厂商",
                   "联系人",
                   "联系方式",
                   "关键词",
                   "数据来源",
                   "备注"
           };
           XSSFRow headerRow = sheet.createRow(0);
           for (int j = 0; j < labels.length; j++) {
               XSSFCell countryCell = headerRow.createCell(j);
               countryCell.setCellValue(labels[j]);
           }
           templateDownloadProduct(labels.length,sheet,workbook);
           templateDownloadProductAdaptation(adLabels.length,adSheet,workbook);
           response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
           response.setCharacterEncoding("utf-8");
           workbook.write(response.getOutputStream());
       } catch (IOException e) {
           throw new RuntimeException(e);
       } finally {
           workbook.close();
       }
    }

    /**
     * 产品制作模板
     * @param len
     */
    public void templateDownloadProduct(int len, XSSFSheet sheet,XSSFWorkbook workbook ){
        XSSFRow row = sheet.createRow(1);
        for (int i = 0; i < len; i++) {
            Cell cell = row.createCell(i);
            if(i == 3){
                List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                String[] dictLabels = new String[productIndustry.size()];
                for (int j = 0; j < productIndustry.size(); j++) {
                    dictLabels[j] = productIndustry.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }

        }
    }
    /**
     * 产品适配信息制作模板
     * @param len
     */
    public void templateDownloadProductAdaptation(int len, XSSFSheet sheet,XSSFWorkbook workbook ){
        XSSFRow row = sheet.createRow(1);
        for (int i = 0; i < len; i++) {
            Cell cell = row.createCell(i);
            if(i == 1){
                List<SysDictData> auditiingOs = sysDictDataMapper.selectDictDataByType("audition_os");
                String[] dictLabels = new String[auditiingOs.size()];
                for (int j = 0; j < auditiingOs.size(); j++) {
                    dictLabels[j] = auditiingOs.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            适配时间
            if(i == 2){
                // 设置日期格式
                String dateFormat = "yyyy-mm-dd";
                DataFormat dataFormat = workbook.createDataFormat();
                CellStyle dateStyle = workbook.createCellStyle();
                dateStyle.setDataFormat(dataFormat.getFormat(dateFormat));
                cell.setCellStyle(dateStyle);
            }
//            适配OS类型
            if(i == 3){
                List<SysDictData> auditiingOsType = sysDictDataMapper.selectDictDataByType("auditiing_os_type");
                String[] dictLabels = new String[auditiingOsType.size()];
                for (int j = 0; j < auditiingOsType.size(); j++) {
                    dictLabels[j] = auditiingOsType.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            适配状态
            if(i == 4){

                List<SysDictData> auditingStatus = sysDictDataMapper.selectDictDataByType("auditing_status");
                String[] dictLabels = new String[auditingStatus.size()];
                for (int j = 0; j < auditingStatus.size(); j++) {
                    dictLabels[j] = auditingStatus.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            兼容等级
            if(i == 6){

                List<SysDictData> compatibilityLevel = sysDictDataMapper.selectDictDataByType("compatibility_level");
                String[] dictLabels = new String[compatibilityLevel.size()];
                for (int j = 0; j < compatibilityLevel.size(); j++) {
                    dictLabels[j] = compatibilityLevel.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            认证状态
            if(i == 8){

                List<SysDictData> certificationStatus = sysDictDataMapper.selectDictDataByType("certification_status");
                String[] dictLabels = new String[certificationStatus.size()];
                for (int j = 0; j < certificationStatus.size(); j++) {
                    dictLabels[j] = certificationStatus.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            适配平台
            if(i == 9){
                List<SysDictData> adaptationPlatform = sysDictDataMapper.selectDictDataByType("adaptation_platform");
                String[] dictLabels = new String[adaptationPlatform.size()];
                for (int j = 0; j < adaptationPlatform.size(); j++) {
                    dictLabels[j] = adaptationPlatform.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            收费/免费
            if(i == 10){
                List<SysDictData> auditingCost = sysDictDataMapper.selectDictDataByType("auditing_cost");
                String[] dictLabels = new String[auditingCost.size()];
                for (int j = 0; j < auditingCost.size(); j++) {
                    dictLabels[j] = auditingCost.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            适配CPU型号
            if(i == 11){
                List<SysDictData> adaptedCpuModel = sysDictDataMapper.selectDictDataByType("adapted_cpu_model");
                String[] dictLabels = new String[adaptedCpuModel.size()];
                for (int j = 0; j < adaptedCpuModel.size(); j++) {
                    dictLabels[j] = adaptedCpuModel.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            上架情况
            if(i == 12){
                List<SysDictData> auditingListing = sysDictDataMapper.selectDictDataByType("auditing_listing");
                String[] dictLabels = new String[auditingListing.size()];
                for (int j = 0; j < auditingListing.size(); j++) {
                    dictLabels[j] = auditingListing.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
//            适配验证情况
            if(i == 13){
                List<SysDictData> adaptationVerificationStatus = sysDictDataMapper.selectDictDataByType("adaptation_verification_status");
                String[] dictLabels = new String[adaptationVerificationStatus.size()];
                for (int j = 0; j < adaptationVerificationStatus.size(); j++) {
                    dictLabels[j] = adaptationVerificationStatus.get(j).getDictLabel();
                }
                // 设置单元格数据验证
                DataValidationHelper validationHelper = new XSSFDataValidationHelper(sheet);
                DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(dictLabels);
                CellRangeAddressList addressList = new CellRangeAddressList(0, 400, i, i);
                DataValidation validation = validationHelper.createValidation(constraint, addressList);
                sheet.addValidationData(validation);
            }
        }
    }
    /**
     * 导入产品信息模板
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int templateRender(MultipartFile file) throws IOException, ParseException {
        // 创建工作簿对象
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        Map<String, ProductAdaptationVo> stringProductAdaptationVoMap = templateRenderProduct(workbook);
        HashMap<String, List<ProductAdaptation>> stringListHashMap = templateRenderProductAdaptation(workbook);
        Set<String> keys = stringProductAdaptationVoMap.keySet();
        for (String key :
                keys) {
            ProductAdaptationVo productAdaptationVo = stringProductAdaptationVoMap.get(key);
            productAdaptationVo.setProductAdaptations(stringListHashMap.get(key));
            insertProduct(productAdaptationVo);
        }
        workbook.close();
        return 1;
    }

    public Map<String,ProductAdaptationVo> templateRenderProduct(Workbook workbook){
        Map<String,ProductAdaptationVo> mapProductAdaptationVo = new HashMap();

        Sheet sheet = workbook.getSheetAt(0);
        int i = 0;
        ProductAdaptationVo productAdaptationVo = new ProductAdaptationVo();
        // 遍历行
        for (Row row : sheet) {
            if(i == 0){
                i++;
                continue;
            }

            int j = 0;
            String key = "";

            // 遍历单元格
            for (Cell cell : row) {
                // 获取单元格的值
                CellType type = cell.getCellType();
                String value = "";
                if (type == CellType.STRING) {
                    value = cell.getStringCellValue();

                } else if (type == CellType.NUMERIC) {
                    value = String.valueOf(cell.getNumericCellValue());

                } else if (type == CellType.BOOLEAN) {
                    value = String.valueOf(cell.getBooleanCellValue());
                }
                if(j == 0){
                    key = value;
//                    产品名称
                }else if(j == 1){
                    productAdaptationVo.setpName(value);
//                    产品类型
                }else if(j == 2){
                    value = value.replace("-",",");
                    ProductType productType = new ProductType();
                    productType.setLevelName(value);
                    List<ProductType> productTypes = productTypeMapper.selectProductTypeList(productType);
                    if(productTypes.size() > 0 ){
                        productAdaptationVo.setpType(productTypes.get(0).getLevelCode());
                    }
//行业
                }else if(j == 3){
                    List<SysDictData> productIndustry = sysDictDataMapper.selectDictDataByType("product_industry");
                    for (int K= 0; K < productIndustry.size(); K++) {
                        if (value.equals(productIndustry.get(K).getDictLabel())) {
                            productAdaptationVo.setpIndustry(productIndustry.get(K).getDictValue());
                            break;
                        }
                    }
//                    版本型号
                }else if(j == 4){
                    productAdaptationVo.setpVersion(value);
//                    产品介绍
                }else if(j == 5){
                    productAdaptationVo.setpIntroduce(value);
//                    厂商
                }else if(j == 6){
                    productAdaptationVo.setpManufacturer(value);
//                    联系人
                }else if(j == 7){
                    productAdaptationVo.setpContacts(value);
//                    联系方式
                }else if(j == 8){
                    productAdaptationVo.setpTel(value);
//                    关键词
                }else if(j == 9){
                    productAdaptationVo.setpKeyword(value);
//                    数据来源
                }else if(j == 10){
                    productAdaptationVo.setpDataSource(value);
//                    备注
                }else if(j == 11){
                    productAdaptationVo.setRemark(value);
                }
                j++;
            }
            mapProductAdaptationVo.put(key,productAdaptationVo);
        }
        return mapProductAdaptationVo;
    }
    public HashMap<String, List<ProductAdaptation>> templateRenderProductAdaptation(Workbook workbook) throws ParseException {
        HashMap<String, List<ProductAdaptation>> mapAdaptation = new HashMap<>();
        Sheet sheet = workbook.getSheetAt(1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int i = 0;

        // 遍历行
        for (Row row : sheet) {
            if(i == 0){
                i++;
                continue;
            }

            int j = 0;
            String key = "";
            ProductAdaptation productAdaptation = new ProductAdaptation();
            // 遍历单元格
            for (Cell cell : row) {

                // 获取单元格的值
                CellType type = cell.getCellType();
                String value = "";
                if (type == CellType.STRING) {
                    value = cell.getStringCellValue();

                } else if (type == CellType.NUMERIC) {
                    if(j == 2){
                        value = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                    }else{
                        value = String.valueOf(cell.getNumericCellValue());
                    }

                } else if (type == CellType.BOOLEAN) {
                    value = String.valueOf(cell.getBooleanCellValue());
                }

                if(j == 0){
                    key = value;

                }else if(j == 1){
                    List<SysDictData> auditiingOs = sysDictDataMapper.selectDictDataByType("audition_os");
                    for (int K= 0; K < auditiingOs.size(); K++) {
                        if (value.equals(auditiingOs.get(K).getDictLabel())) {
                            productAdaptation.setPaOs(auditiingOs.get(K).getDictValue());
                            break;
                        }
                    }
                    //            适配时间
                }else if(j == 2){
                    productAdaptation.setPaTime(sdf.parse(value));
                    //            适配OS类型
                }else if(j == 3){
                    List<SysDictData> auditiingOsType = sysDictDataMapper.selectDictDataByType("auditiing_os_type");
                    for (int K= 0; K < auditiingOsType.size(); K++) {
                        if (value.equals(auditiingOsType.get(K).getDictLabel())) {
                            productAdaptation.setPaType(auditiingOsType.get(K).getDictValue());
                            break;
                        }
                    }
                    //            适配状态
                }else if(j == 4){
                    List<SysDictData> auditingStatus = sysDictDataMapper.selectDictDataByType("auditing_status");
                    for (int K= 0; K < auditingStatus.size(); K++) {
                        if (value.equals(auditingStatus.get(K).getDictLabel())) {
                            productAdaptation.setPaState(auditingStatus.get(K).getDictValue());
                            break;
                        }
                    }
//                    适配OS版本
                }else if(j == 5){
                    productAdaptation.setPaVersion(value);
//            兼容等级
                }else if(j == 6){
                    List<SysDictData> compatibilityLevel = sysDictDataMapper.selectDictDataByType("compatibility_level");
                    for (int K= 0; K < compatibilityLevel.size(); K++) {
                        if (value.equals(compatibilityLevel.get(K).getDictLabel())) {
                            productAdaptation.setPaLevel(compatibilityLevel.get(K).getDictValue());
                            break;
                        }
                    }
//                    OS小版本
                }else if(j == 7){
                    productAdaptation.setPaMinVersion(value);
                    //            认证状态
                }else if(j == 8){
                    List<SysDictData> certificationStatus = sysDictDataMapper.selectDictDataByType("certification_status");
                    for (int K= 0; K < certificationStatus.size(); K++) {
                        if (value.equals(certificationStatus.get(K).getDictLabel())) {
                            productAdaptation.setPaAuthenticationStatus(certificationStatus.get(K).getDictValue());
                            break;
                        }
                    }
                    //            适配平台
                }else if(j == 9){
                    List<SysDictData> adaptationPlatform = sysDictDataMapper.selectDictDataByType("adaptation_platform");
                    for (int K= 0; K < adaptationPlatform.size(); K++) {
                        if (value.equals(adaptationPlatform.get(K).getDictLabel())) {
                            productAdaptation.setPaPlatform(adaptationPlatform.get(K).getDictValue());
                            break;
                        }
                    }
                    //            收费/免费
                }else if(j == 10){
                    List<SysDictData> auditingCost = sysDictDataMapper.selectDictDataByType("auditing_cost");
                    for (int K= 0; K < auditingCost.size(); K++) {
                        if (value.equals(auditingCost.get(K).getDictLabel())) {
                            productAdaptation.setPaCost(auditingCost.get(K).getDictValue());
                            break;
                        }
                    }
                    //            适配CPU型号
                }else if(j == 11){
                    List<SysDictData> adaptedCpuModel = sysDictDataMapper.selectDictDataByType("adapted_cpu_model");
                    for (int K= 0; K < adaptedCpuModel.size(); K++) {
                        if (value.equals(adaptedCpuModel.get(K).getDictLabel())) {
                            productAdaptation.setPaCpu(adaptedCpuModel.get(K).getDictValue());
                            break;
                        }
                    }
                    //            上架情况
                }else if(j == 12){
                    List<SysDictData> auditingListing = sysDictDataMapper.selectDictDataByType("auditing_listing");
                    for (int K= 0; K < auditingListing.size(); K++) {
                        if (value.equals(auditingListing.get(K).getDictLabel())) {
                            productAdaptation.setPaListing(auditingListing.get(K).getDictValue());
                            break;
                        }
                    }
                }else if(j == 13){
                    List<SysDictData> adaptationVerificationStatus = sysDictDataMapper.selectDictDataByType("adaptation_verification_status");
                    for (int K= 0; K < adaptationVerificationStatus.size(); K++) {
                        if (value.equals(adaptationVerificationStatus.get(K).getDictLabel())) {
                            productAdaptation.setPaValidate(adaptationVerificationStatus.get(K).getDictValue());
                            break;
                        }
                    }
//                    备注
                }else if(j == 14){
                    productAdaptation.setPaRemark(value);
                }
                j++;
            }
            List<ProductAdaptation> productAdaptations = mapAdaptation.get(key);
            if(productAdaptations == null){
                productAdaptations = new ArrayList<>();
                productAdaptations.add(productAdaptation);
                mapAdaptation.put(key,productAdaptations);
            }else{
                productAdaptations.add(productAdaptation);
            }
        }

        return mapAdaptation;
    }

    /**
     * 产品审核
     * @param auditingEnterpriseBase 产品审核字段
     * @return
     */
    public int auditingProduct(AuditingEnterpriseBase auditingEnterpriseBase){
        Product product = new Product();
        product.setId(auditingEnterpriseBase.getaPId());
        product.setpStatus(auditingEnterpriseBase.getEbState());
        product.setUpdateBy(auditingEnterpriseBase.getCreateBy());
        product.setUpdateTime(DateUtils.getNowDate());
        int i = productMapper.updateProduct(product);
        if(i>0){
            Auditing auditing = new Auditing();
            auditing.setpName("product");
            auditing.setaPId(auditingEnterpriseBase.getaPId());
            auditing.setaInfo(auditingEnterpriseBase.getaInfo());
            auditing.setaState(auditingEnterpriseBase.getEbState());
            auditing.setCreateTime(DateUtils.getNowDate());
            auditing.setCreateBy(auditingEnterpriseBase.getCreateBy());
            return auditingMapper.insertAuditing(auditing);
        }
        return 0;
    }
}
